package com.zsc.oj.zojcodesendbox.judge;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.zsc.oj.zojcodesendbox.utils.ProcessUtils;
import com.zsc.oj.zojcodesendbox.utils.model.ExecuteMessage;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * java docker沙箱
 */
@Component
public class JavaDockerCodeSendBox extends JavaCodeSendBoxTemplate{
    private static final String GLOBAL_CODE_DIR_NAME = "tempCode";

    private static final String FILE_NAME = "Main.java";

    private static final boolean IS_PULL = true;

    public static final Long TIME_OUT = 5000L;

//    public static void main(String[] args) {
//        JavaDockerCodeSendBox javaDockerCodeSendBox = new JavaDockerCodeSendBox();
//        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
//        //读取代码
//        String code = ResourceUtil.readStr("test/Main.java", StandardCharsets.UTF_8);
//        executeCodeRequest.setCode(code);
//        executeCodeRequest.setLanguage("java");
//        executeCodeRequest.setInputList(Arrays.asList("1 2","1 3"));
//        ExecuteCodeResponse executeCodeResponse = javaDockerCodeSendBox.ExecuteCode(executeCodeRequest);
//        System.out.println(executeCodeResponse);
//    }

    /**
     * 将运行代码的步骤交由docker进行运行
     * @param inputList：输入用例
     * @param userCodeFile：用户代码文件
     * @return
     */
    @Override
    public List<ExecuteMessage> runCode(List<String> inputList, File userCodeFile) {
        // 创建容器，将编译后的文件放到容器中

        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();

        //创建docker客户端连接
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();

        //镜像文件
        String image = "openjdk:8-alpine";
        if(IS_PULL){
            //拉取镜像
            //创建拉取镜像的对象
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback(){
                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd.exec(pullImageResultCallback).awaitCompletion();
                System.out.println("拉取镜像成功");
            } catch (InterruptedException e) {
                System.out.println("拉取镜像失败");
                throw new RuntimeException(e);
            }
        }


        //创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);

        //设置容器的配置，将编译完成的文件设置到容器中【Volume：放到容器的哪个目录下】
        HostConfig hostConfig = new HostConfig();
        hostConfig.setBinds(new Bind(userCodeParentPath,new Volume("/app")));
        //限制运行内存
        hostConfig.withMemory(100 * 1000 * 1000L);

        CreateContainerResponse createContainerResponse = containerCmd
                //获取容器的输入和输出
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                //设置一个交互终端
                .withTty(true)
                .withHostConfig(hostConfig)
                //禁用网络资源
                .withNetworkDisabled(true)
                .exec();

        //容器id
        String containerId = createContainerResponse.getId();

        //启动容器
        dockerClient.startContainerCmd(containerId).exec();

        //创建执行编译文件的命令
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String input : inputList) {

            //定义计时器开始计时
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            //原生的执行命令：docker exec gifted_hoover java -cp /app Main 1 3
            String[] inputArgsArray = input.split(" ");
            String[] execJavaClassCmd = ArrayUtil.append(new String[]{"java","-cp","/app","Main"},inputArgsArray);
            ExecCreateCmd execCreateCmd = dockerClient.execCreateCmd(containerId);
            ExecCreateCmdResponse execCreateCmdResponse = execCreateCmd
                    //执行的命令
                    .withCmd(execJavaClassCmd)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("创建执行命令" + execCreateCmdResponse);

            //执行命令
            ExecuteMessage executeMessage = new ExecuteMessage();

            final String[] SuccessMessage = {null};
            final String[] ErrorMessage = {null};
            final Long[] maxMemory = {0L};
            final boolean[] timeout = {true};
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback(){

                //超时中断回调函数
                @Override
                public void onComplete() {
                    //如果执行完成表示未超时
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    //StreamType是输出的结结果
                    StreamType streamType = frame.getStreamType();
                    if(StreamType.STDERR.equals(streamType)){
                        ErrorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + ErrorMessage[0]);
                    }else{
                        SuccessMessage[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + SuccessMessage[0]);
                    }
                    super.onNext(frame);
                }
            };

            //获取最大内存
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }
                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            });

            try {
                dockerClient.execStartCmd(execCreateCmdResponse.getId())
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MILLISECONDS);
                //结束计时
                stopWatch.stop();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }

            executeMessage.setErrorMessage(ErrorMessage[0]);
            executeMessage.setSuccessMessage(SuccessMessage[0]);
            executeMessage.setMemory(maxMemory[0]);
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
            executeMessageList.add(executeMessage);
        }
        return executeMessageList;
    }
}
